package com.yugao.fintech.antelope.codegen.manager;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yugao.fintech.antelope.codegen.mapper.GenTableMapper;
import com.yugao.fintech.antelope.codegen.model.entity.GenTable;
import com.yugao.fintech.antelope.codegen.model.rqrs.GenTablePageRQ;
import com.yugao.fintech.framework.assistant.utils.StringUtils;
import com.yugao.fintech.framework.core.page.PageModel;
import com.yugao.fintech.framework.core.page.TableSupport;
import com.yugao.fintech.framework.mybatisplus.utils.PageUtil;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Objects;


@Repository
public class GenTableManager extends ServiceImpl<GenTableMapper, GenTable> implements IService<GenTable> {
    @Autowired
    private GenTableMapper genTableMapper;

    public void saveOrUpdateGenTable(GenTable req) {
        String tableName = req.getTableName();
        LambdaQueryWrapper<GenTable> wrapper = GenTable.lqw()
                .eq(GenTable::getTableName, tableName).eq(GenTable::getDatasourceId, req.getDatasourceId());
        GenTable genTable = genTableMapper.selectOne(wrapper);
        if (Objects.nonNull(genTable)) {
            req.setId(genTable.getId());
            genTableMapper.updateById(req);
        } else {
            genTableMapper.insert(req);
        }
    }

    public IPage<GenTable> pageGenTable(GenTablePageRQ req) {
        PageModel pageModel = TableSupport.buildPageRequest();
        LambdaQueryWrapper<GenTable> wrapper = GenTable.lqw()
                .like(StringUtils.isNotEmpty(req.getTableName()), GenTable::getTableName, req.getTableName())
                .like(StringUtils.isNotEmpty(req.getTableComment()), GenTable::getTableComment, req.getTableComment())
                .eq(Objects.nonNull(req.getDatasourceId()), GenTable::getDatasourceId, req.getDatasourceId())
                .orderByDesc(GenTable::getUpdatedAt);
        return this.page(PageUtil.to(pageModel), wrapper);
    }

    public List<GenTable> listByDatasourceId(Long datasourceId) {
        LambdaQueryWrapper<GenTable> wrapper = GenTable.lqw().eq(GenTable::getDatasourceId, datasourceId);
        return this.list(wrapper);
    }
}
